package cs236369.webserver;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.http.params.HttpParams;

import cs236369.webserver.queue.managers.SocketTaskManager;

class RequestListenerThread extends Thread {
	private final ServerSocket serverSocket;
	// private final HttpParams params;
	// private final HttpService httpService;
	private final SocketTaskManager socketTaskManager;

	// TODO - remove unused things
	public RequestListenerThread(int port, HttpParams params,
			SocketTaskManager socketTaskManager) throws IOException {
		this.socketTaskManager = socketTaskManager;
		this.serverSocket = new ServerSocket(port);
		// this.params = params;
		// // Set up the HTTP protocol processor
		// HttpProcessor httpproc = new ImmutableHttpProcessor(
		// new HttpResponseInterceptor[] { new ResponseDate(),
		// new ResponseServer(), new ResponseContent(),
		// new ResponseConnControl() });
		// // Set up request handlers
		// HttpRequestHandlerRegistry reqistry = new
		// HttpRequestHandlerRegistry();
		// reqistry.register("*", new HttpReqHandler());
		// // Set up the HTTP service
		// this.httpService = new HttpService(httpproc,
		// new DefaultConnectionReuseStrategy(),
		// new DefaultHttpResponseFactory(), reqistry, this.params);
	}

	public void run() {
		System.out.println("Listening on port "
				+ this.serverSocket.getLocalPort());

		while (!Thread.interrupted()) {
			try {
				// Set up HTTP connection
				Socket socket = this.serverSocket.accept();
				socketTaskManager.enQueue(socket);
			} catch (InterruptedIOException ex) {
				break;
			} catch (IOException e) {
				System.err.println("I/O error initialising connection thread: "
						+ e.getMessage());
				break;
			}
		}
	}
}
